extends Node2D
# 楼层/楼梯过渡测试脚本：
# - Stair1Area：进入时仅临时切换导航层为 3，离开后切回层 2（物理与导航）
# - Stair2Area：进入时将物理层/掩码与导航层统一切换到层 3
# - 所有层切换均作用于进入区域的实体根节点（CharacterBody2D）

@onready var stair_area: Area2D = get_node("NavRegion/Stair1Area") as Area2D
@onready var stair2_area: Area2D = get_node("NavRegion/Stair2Area") as Area2D

func _ready() -> void:
	stair_area.body_entered.connect(_on_stair_body_entered)
	stair2_area.body_entered.connect(_on_stair2_body_entered)
 

func _on_stair_body_entered(body: Node) -> void:
	if not (body is CharacterBody2D):
		return
	var ent := body as CharacterBody2D
	var vy: float = ent.velocity.y
	if vy < 0.0:
		_switch_entity_to_layer(ent, 2)
	elif vy > 0.0:
		_switch_entity_to_layer(ent, 1)


func _on_stair2_body_entered(body: Node) -> void:
	if not (body is CharacterBody2D):
		return
	var ent := body as CharacterBody2D
	var vy: float = ent.velocity.y
	if vy < 0.0:
		_switch_entity_to_layer(ent, 3)
	elif vy > 0.0:
		_switch_entity_to_layer(ent, 2)

func _switch_entity_to_layer(n: Node, layer: int) -> void:
	var ent := _find_entity_root(n)
	var bit := 1 << (layer - 1)
	var co := ent as CollisionObject2D
	co.collision_layer = bit
	co.collision_mask = bit
	var agent := ent.get_node("NavigationAgent2D") as NavigationAgent2D
	agent.navigation_layers = bit
	print("对象%s已切换层级: 物理层=%d 掩码=%d 导航层=%d" % [ent.name, (ent as CollisionObject2D).collision_layer, (ent as CollisionObject2D).collision_mask, agent.navigation_layers])

 
func _find_entity_root(n: Node) -> Node2D:
	# 从任意子节点向上追溯，找到所属的 CharacterBody2D 作为实体根
	var p := n
	while p:
		if p is CharacterBody2D:
			return p as Node2D
		p = p.get_parent()
	return null
